<style lang="scss" src="./index.scss" scoped></style>
<template>
    <div class="drag-tag-form-box">
        <div class="drag-tag-form__title">表格设置</div>
        <div class="drag-tag-form__table">
            <ul class="drag-tag-form__th">
                <template v-for="item in tableColumn">
                    <li class="drag-tag-form__td" :class="[item.prop]" :key="item.prop">
                        <template v-if="item.prop === 'required'">
                            <el-checkbox v-model="requiredChecked">{{item.label}}</el-checkbox>
                        </template>
                        <template v-else>
                            {{item.label}}
                        </template>
                    </li>
                </template>
                <li class="drag-tag-form__td operator">
                    操作
                </li>
            </ul>
            <draggable
                class="drag-tag-form__tbody"
                tag="div"
                :list="list"
                filter=".no-drag"
                v-bind="dragOptions"
                group="tagModel"
                @change="onDragChange"
                @start="drag = true"
                @end="drag = false"
            >
                <transition-group type="transition" :name="!drag ? 'flip-list' : null">
                    <ul v-for="(dataItem,index) in currentList" class="drag-tag-form__tr" :key="dataItem._key">
                        <template v-for="item in tableColumn">
                            <li class="drag-tag-form__td" :class="[item.prop]" :key="item.prop">
                                <template v-if="item.prop === 'name'">
                                    <el-autocomplete
                                        class="inline-input"
                                        :disabled="!!dataItem.id"
                                        v-model="dataItem[item.prop]"
                                        :fetch-suggestions="querySearch"
                                        :maxlength="100"
                                        placeholder="请输入内容"
                                        :trigger-on-focus="false"
                                        @select="(subItem)=> handleSelect(subItem, index)"
                                    ></el-autocomplete>
                                </template>
                                <template v-else-if="item.prop === 'type'">
                                    <el-select
                                        clearable
                                        :disabled="!!dataItem.id"
                                        v-model="dataItem.typeValue"
                                        @change="handleSelectChange('type', dataItem.typeValue, index)"
                                        placeholder="请选择类型">
                                        <el-option
                                            v-for="item in typeList"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value">
                                        </el-option>
                                    </el-select>
                                </template>
                                <template v-else-if="item.prop === 'unit'">
                                    <el-select
                                        clearable
                                        :disabled="!!dataItem.id"
                                        v-model="dataItem.unitValue"
                                        @change="handleSelectChange('unit', dataItem.unitValue, index)"
                                        placeholder="无">
                                        <el-option
                                            v-for="item in unitList"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value">
                                        </el-option>
                                    </el-select>
                                </template>
                                <template v-else-if="item.prop === 'optionValueText'">
                                    <div class="drag-tag-form__sub-text">
                                        {{dataItem[item.prop]}}{{dataItem[item.prop] && dataItem.optionValueTextNew ? "," : ""}}{{dataItem.optionValueTextNew}}
                                    </div>
                                    <el-button
                                        v-if="dataItem.typeValue === 'select' || dataItem.typeValue === 'cascader'"
                                        type="primary"
                                        size="mini"
                                        @click="updateValue(dataItem, index)"
                                        icon="el-icon-edit"></el-button>
                                </template>
                                <template v-else-if="item.prop === 'required'">
                                    <el-checkbox v-model="dataItem[item.prop]">必填</el-checkbox>
                                </template>
                                <template v-else>
                                    {{dataItem[item.prop]}}
                                </template>
                            </li>
                        </template>
                        <li class="drag-tag-form__td operator">
                            <el-button @click.stop="onDel(dataItem, index)">删除</el-button>
                        </li>
                    </ul>
                </transition-group>
            </draggable>
            <div class="drag-tag-form__group">
                <el-button v-if="_isOperationPage" plain @click="onAdd">添加表格选项</el-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Mixins, PropSync } from "vue-property-decorator";
import draggable from "vuedraggable";
import { dialogForm } from "./form";
import FormMixin from "@/mixins/form.mixin.base";
@Component({
    components: {
        draggable
    }
})
export default class DragTagForm extends Mixins(FormMixin) {
    get _isOperationPage() {
        return this.$route.name === "OperationModuleManageForm";
    }

    pointCancel: any = null;
    drag = false;
    get dragOptions() {
        return {
            animation: 200,
            disabled: false,
            ghostClass: "ghost"
        };
    }

    get requiredChecked(): boolean {
        const _length = this.currentList.filter((item: any) => item.required).length;
        return _length === this.currentList.length;
    }

    set requiredChecked(val: boolean) {
        for (let i = 0; i < this.currentList.length; i++) {
            const cur = this.currentList[i];
            cur.required = val;
        }
    }

    typeList = [
        { value: "input-num", label: "数字" },
        { value: "input-alpha", label: "字母" },
        { value: "input-phone", label: "手机号" },
        { value: "input-email", label: "Email" },
        { value: "input-text", label: "普通文本" },
        { value: "input-textarea", label: "多行文本" },
        { value: "input-date", label: "时间选择" },
        { value: "location", label: "定位" },
        { value: "upload-img", label: "上传图片" },
        { value: "upload-video", label: "上传视频" },
        { value: "upload-record", label: "上传录音" },
        { value: "upload-file", label: "上传文件" },
        { value: "select", label: "单选" },
        { value: "cascader", label: "多选" }
    ];

    unitList = [
        // { value: "input-num", label: "数字" },
        // { value: "input-alpha", label: "字母" },
        // { value: "input-phone", label: "手机号" },
        // { value: "input-email", label: "Email" },
        // { value: "input-text", label: "普通文本" },
        // { value: "input-textarea", label: "多行文本" },
        // { value: "input-date", label: "时间选择" },
        // { value: "location", label: "定位" },
        // { value: "upload-img", label: "上传图片" },
        // { value: "select", label: "单选" },
        // { value: "cascader", label: "多选" }
    ];

    // 表格渲染格
    tableColumn = [
        { label: '标题', prop: 'name' },
        { label: '类型', prop: 'type' },
        { label: '单位', prop: 'unit' },
        { label: '选项操作', prop: 'optionValueText' },
        { label: '必填', prop: 'required' }
    ]

    @PropSync(
        'list',
        {
            type: Array,
            default: () => {
                return [];
            }
        })
    readonly currentList!: any[];

    handleItemClick(item: any, type: string) {
        this.$emit("item-click", item, type);
    }

    mounted() {
        this.initSearchData();
    }

    async initSearchData() {
        try {
            const typeResponse = await this.$server["moduleManage/form/type"]();
            if (typeResponse.data.code !== 200) {
                throw typeResponse.data;
            }
            this.typeList = (typeResponse.data.data || []).map((item: any) => {
                return {
                    id: item.id || "",
                    value: item.value || "",
                    label: item.name || ""
                };
            });
            const unitResponse = await this.$server["moduleManage/form/unit"]();
            if (unitResponse.data.code !== 200) {
                throw unitResponse.data;
            }
            this.unitList = (unitResponse.data.data || []).map((item: any) => {
                return {
                    value: item.id || "",
                    label: item.name || ""
                };
            });
        } catch (error) {
            if (error.cancel) {
                return;
            }
            this.$message.error(error.message || "接口请求错误!");
            throw error;
        }
    }

    onDel(item: any, index: any) {
        this.currentList.splice(index, 1);
    }

    onAdd(item?: any) {
        if (item && item._key) {
            this.currentList.push(this.buildData(item.source || {}));
        } else {
            const obj: any = this.$key2Name({
                type: "input-text",
                list: this.typeList,
                key: "value"
            }, "obj");
            this.currentList.push(this.buildData({
                valueKindId: obj.id,
                valueLabel: obj.label,
                valueKindName: obj.value
            }));
        }
    }

    updateValue(item: any) {
        dialogForm({
            value: item.optionValueText,
            valueNew: item.optionValueTextNew,
            sure: (vm: any, model: any) => {
                vm.close();
                item.optionValueTextNew = model.value;
            }
        });
    }

    async querySearch(queryString: any, cb: any) {
        let results: any[] = [];
        const response = await this.$server["moduleManage/form/queryAuto"]({
            loader: false,
            data: {
                name: queryString,
                currentPageSize: 1,
                pageSize: 100
            },
            cancelToken: (c: any) => {
                if (this.pointCancel) {
                    this.pointCancel("不需要渲染");
                }
                this.pointCancel = c;
            }
        });
        if (this.responseHasError(response)) {
            cb(results);
            return;
        }
        const data = response.data.data || [];
        results = data.map((cur: any) => {
            return {
                value: cur.name,
                source: cur
            };
        });
        cb(results);
    }

    handleSelect(item: any, index: any) {
        const cur: any = item.source || {};
        const newItem = this.buildData(cur);
        newItem._key = this.currentList[index]._key;
        this.$set(this.currentList, index, newItem);
    }

    buildData(cur: any) {
        let optionValueText = "";
        if (
            cur.valueLabel === "select" ||
            cur.valueLabel === "cascader"
        ) {
            (cur.optionIds || []).forEach(
                (subCur: any, index: any) => {
                    optionValueText +=
                        (index === 0 ? "" : ",") + subCur.name;
                }
            );
        }
        return {
            _key: this.currentList.length + '-' + (+new Date()),
            id: cur.id,
            name: cur.name || "",
            typeId: cur.valueKindId || "",
            typeValue: cur.valueLabel || "",
            type: cur.valueKindName || "",
            unitValue: cur.unitKindId || "",
            unit: cur.unitKindName || "",
            rules: cur.rules || "",
            optionId: cur.optionId || "",
            optionValueText: optionValueText,
            optionValueTextNew: "",
            required: this.requiredChecked || !!cur.required
        };
    }

    handleSelectChange(type: string, value: any, index: any) {
        if (type === "unit") {
            this.currentList[index][type] = this.$key2Name({
                type: value,
                list: this.unitList,
                key: "value",
                name: "label"
            });
        }
        if (type === "type") {
            const obj: any = this.$key2Name({
                type: value,
                list: this.typeList,
                key: "value"
            }, "obj");
            this.currentList[index][type] = obj.label;
            this.currentList[index].typeId = obj.id;
        }
    }

    submit() {
        const res: any = {
            result: true,
            msg: ""
        };
        for (let i = 0; i < this.currentList.length; i++) {
            const cur = this.currentList[i];
            if (!cur.name) {
                res.result = false;
                res.msg = `第${i + 1}项的标题不能为空`;
                break;
            }
            if (!cur.typeValue) {
                res.result = false;
                res.msg = `第${i + 1}项的类型不能为空`;
                break;
            }
        }
        return res;
    }

    onDragChange(item: any) {
        const { newIndex, element } = item.added;
        this.$set(this.currentList, newIndex, this.buildData(element.source || {}));
    }
}
</script>
